Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

function yahooAPI()
{
	this.zip="";
}

yahooAPI.prototype = {
	classDescription: "yahoo API",
	classID:          Components.ID("{3037837d-57ab-4751-b439-bbe3107dd6a8}"),
	contractID:       "@weather-forecaster/yahooAPI;1",
	QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIyahooAPI]),
	
	parseToJSON: function(text)
	{
		var input = JSON.parse(text);
		////
		try
		{
			var api_name = "Yahoo!";
			var city     = input.query.results.channel.location.city;
			var state    = input.query.results.channel.location.region;
			var tempF    = input.query.results.channel.item.condition.temp;
			var tempC    = Math.round((((parseInt(tempF)-32)*5)/9)*100)/100;
			var humidity = input.query.results.channel.atmosphere.humidity;
			var weather  = input.query.results.channel.item.condition.text;
			var wind_mph = input.query.results.channel.wind.speed;
			var wind_kph = Math.round((wind_mph*1.60934)*100)/100;
			////		
			var output = '{\n\t"api_name":"'+api_name+'",\n\t"city":"'+city;
			output += '",\n\t"state":"'+state+'",\n\t"zip":"'+this.zip;
			output += '",\n\t"tempF":"'+tempF+'",\n\t"tempC":"'+tempC;
			output += '",\n\t"humidity":"'+humidity+'",\n\t"weather":"'+weather;
			output += '",\n\t"wind_mph":"'+wind_mph+'",\n\t"wind_kph":"'+wind_kph;
			output += '"\n}';
			return output;
		}
		catch (anError)
		{
			var retval = "ERROR";
			return retval;		
		}
	},

	/*
		get weather, save as file, return file contents
		expectations:
			- url => sanitized string, built up by class code below
	*/
	getWeatherByUrl: function(url)
	{
		const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1");
		var request = XMLHttpRequest();
		
		request.open("GET",url,false);
		request.send(null);

		return this.parseToJSON(request.responseText);
	},

	/*
		return the weather in a known format
		expectations:
			zip => 5 digit
	*/
	getWeatherByZipCode: function(zip) 
	{ 
		this.zip = zip;
		var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location="';
	
		//zip code lookups do not depend on state, so just add in the zip
		var zExt = zip + '"&format=json';
		url += zExt;

		//"http://weather.yahooapis.com/forecastrss?p="+zip;
	
		var retval = this.getWeatherByUrl(url);
		return retval;
	},

	isValidZip: function(zip)
	{
		var result = this.getWeatherByZipCode(zip);
		if (result == "ERROR")
			return false;

		return true;
	}
};

var components = [yahooAPI];
if ("generateNSGetFactory" in XPCOMUtils)
  var NSGetFactory = XPCOMUtils.generateNSGetFactory(components);  // Firefox 4.0 and higher
else
  var NSGetModule = XPCOMUtils.generateNSGetModule(components);    // Firefox 3.x
